package com.bankcrm.dao;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Component;

import com.bankcrm.model.User;

@Component
public class UserDao {

	private User user; // injection
	private SessionFactory sessionFactory; //injection
	
	public boolean insertUser(User user) {
		Session session = null; 
		try {		
			session = sessionFactory.openSession();
			session.beginTransaction(); 
			session.save(user); 
			session.getTransaction().commit(); 
		}catch(Exception e) {
			e.printStackTrace();
			session.getTransaction().rollback(); 
			return false; 
		}finally {
			session.close();
		}
		return true;
	}
	
	public boolean deleteUserById(int userId) {
		
		Session session = null; 
		try {		
			session = sessionFactory.openSession();
			session.beginTransaction(); 
			
			String hql = "Delete FROM User Where id=?";
			Query query = session.createQuery(hql)
					.setInteger(0, userId);
			query.executeUpdate();
			
			session.getTransaction().commit(); 
		}catch(Exception e) {
			e.printStackTrace();
			session.getTransaction().rollback(); 
			return false; 
		}finally {
			session.close();
		}
		
		return true;
	}

	public List<User> getAllUsers() {
		List<User> usersList = new ArrayList<User>();
		Session session = null; 
		try {		
			session = sessionFactory.openSession();
			Query query = session.createQuery("from User");
			usersList = query.list(); 
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			session.close();
		}
		return usersList; 
	}
	
	public User getUserById(int userId) {
		Session session = null; 
		try {		
			session = sessionFactory.openSession();
			user = (User) session.get(User.class, userId); 
		}catch(Exception e) {
			e.printStackTrace();
			return null;
		}finally {
			session.close();
		}
		return user; 
	}

	public boolean updateUser(User user) {
		Session session = null; 
		try {		
			session = sessionFactory.openSession();
			session.beginTransaction(); 
			session.update(user); 
			session.getTransaction().commit(); 
		}catch(Exception e) {
			e.printStackTrace();
			session.getTransaction().rollback(); 
			return false; 
		}finally {
			session.close();
		}
		return true;
	}
	
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public User getUser() {
		return user;
	}

	@Resource
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	@Resource
	public void setUser(User user) {
		this.user = user;
	} 
	
}
